<template>
  <div id="graph-container">ceshi</div>
</template>
<script>
import G6 from "@antv/g6";
export default {
  name: "",
  mounted() {
    this.initG6();
  },
  methods: {
    initG6() {
      const width = document.getElementById("graph-container").scrollWidth;
      const height =
        document.getElementById("graph-container").scrollHeight || 500;
      // G6.registerNode('nodeName', options) 进行自定义节点，方便用户开发更加定制化的节点
      G6.registerNode("iconfont", {
        // / 定义的其他方法，都可以在draw里面调用， 如 drawShape、drawLabel 等。
        draw(cfg, group) {
          const {
            backgroundConfig: backgroundStyle,
            style,
            labelCfg: labelStyle
          } = cfg;

          if (backgroundStyle) {
            group.addShape("circle", {
              attrs: {
                x: 0, //圆形图形位置
                y: 0,
                r: cfg.size,
                ...backgroundStyle
                //     description: 'This is node-0.',
                // subdescription: 'This is subdescription of node-0.',
              },
              // must be assigned in G6 3.3 and later versions. it can be any value you want
              name: "circle-shape"
            });
          }

          // 添加图标
          const keyShape = group.addShape("text", {
            attrs: {
              x: 0,
              y: 0,
              fontFamily: "iconfont", // 对应css里面的font-family: "iconfont";
              textAlign: "center",
              textBaseline: "middle",
              text: cfg.text,
              fontSize: cfg.size,
              ...style
            },
            // must be assigned in G6 3.3 and later versions. it can be any value you want
            name: "text-shape1"
          });
          const labelY = backgroundStyle ? cfg.size * 2 : cfg.size;

          group.addShape("text", {
            attrs: {
              x: 0,
              y: labelY,
              textAlign: "center",
              text: cfg.label,
              ...labelStyle.style
            },
            // must be assigned in G6 3.3 and later versions. it can be any value you want
            name: "text-shape1"
          });
          // 动态增加或删除元素
          const COLLAPSE_ICON = function COLLAPSE_ICON(x, y, r) {
            return [
              ["M", x - r, y - r],
              ["a", r, r, 0, 1, 0, r * 2, 0],
              ["a", r, r, 0, 1, 0, -r * 2, 0],
              ["M", x + 2 - r, y - r],
              ["L", x + r - 2, y - r]
            ];
          };
          const EXPAND_ICON = function EXPAND_ICON(x, y, r) {
            return [
              ["M", x - r, y - r],
              ["a", r, r, 0, 1, 0, r * 2, 0],
              ["a", r, r, 0, 1, 0, -r * 2, 0],
              ["M", x + 2 - r, y - r],
              ["L", x + r - 2, y - r],
              ["M", x, y - 2 * r + 2],
              ["L", x, y - 2]
            ];
          };
          // 添加新增图标
          group.addShape("marker", {
            attrs: {
              x: -10,
              y: 40,
              r: 6,
              stroke: "pink",
              cursor: "pointer",
              symbol: EXPAND_ICON
            },
            name: "add-item"
          });
          //添加删除图标
          group.addShape("marker", {
            attrs: {
              x: 15,
              y: 40,
              r: 6,
              stroke: "black",
              cursor: "pointer",
              symbol: COLLAPSE_ICON
            },
            name: "remove-item"
          });
          return keyShape;
        }
      });

      const COLOR = "#40a9ff";
      const graph = new G6.TreeGraph({
        container: "graph-container",
        width: 800,
        height: 900,
        modes: {
          default: [
            "collapse-expand",
            "drag-canvas",
            "drag-node",
            {
              //节点提示框
              type: "tooltip",
              formatText(model) {
                // 提示框内容
                const text = "label:" + model.label;
                return text;
              }
            },
            {
              // 边提示框
              type: "edge-tooltip",
              formatText(model) {
                console.log(model);
                // 边提示框内容
                const text = "label: " + model.label;
                // '<br/> target: ' +
                // model.target +
                // '<br/> weight: ' +
                // model.weight;
                return text;
              }
            }
          ]
        },
        defaultNode: {
          backgroundConfig: {
            backgroundType: "circle",
            fill: COLOR,
            stroke: "LightSkyBlue"
          },
          type: "iconfont",
          size: 12,
          style: {
            fill: "#fff"
          },
          labelCfg: {
            style: {
              fill: COLOR,
              fontSize: 12
            }
          }
        },
        // 布局相关
        layout: {
          // type: 'compactBox',
          type: "mindmap",
          // direction: 'LR',
          direction: "H",
          getId(d) {
            return d.id;
          },
          getHeight() {
            return 50;
          },
          getWidth() {
            return 16;
          },
          getVGap() {
            return 10;
          },
          getHGap() {
            return 50;
          }
        }
      });

      // 超长文本
      const fittingString = (str, maxWidth, fontSize) => {
        const ellipsis = "...";
        const ellipsisLength = G6.Util.getTextSize(ellipsis, fontSize)[0];
        let currentWidth = 0;
        let res = str;
        const pattern = new RegExp("[\u4E00-\u9FA5]+"); // distinguish the Chinese charactors and letters
        str.split("").forEach((letter, i) => {
          if (currentWidth > maxWidth - ellipsisLength) return;
          if (pattern.test(letter)) {
            // Chinese charactors
            currentWidth += fontSize;
          } else {
            // get the width of single letter according to the fontSize
            currentWidth += G6.Util.getLetterWidth(letter, fontSize);
          }
          if (currentWidth > maxWidth - ellipsisLength) {
            res = `${str.substr(0, i)}${ellipsis}`;
          }
        });
        return res;
      };

      const globalFontSize = 12;

      graph.edge(({ target }) => {
        const fill =
          target.get("model").backgroundConfig &&
          target.get("model").backgroundConfig.fill;
        return {
          type: "cubic-horizontal", //边的类型
          color: fill || COLOR,
          label: target.get("model").relation || "",
          labelCfg: {
            //配置标签文本
            style: {
              fill: fill || COLOR,
              fontSize: 12
            }
          }
        };
      });

      const data = {
        isRoot: true,
        id: "Root",
        label:
          "父节点节点或边上的文本超长时，可以通过使用 JS 来计算文本长度，也可以通过使用 \n 来进行换行",
        text: "\ue716", // 对应iconfont.css 里面的content，注意加u，后面的自行修改一下。
        style: {
          fill: "red"
        },
        labelCfg: {
          style: {
            fill: "red"
          }
        },
        backgroundConfig: null, // 自定义项，用于判读是否需要圆背景
        size: 30,
        children: [
          {
            id: "SubTreeNode1",
            label: "circle圆形",
            text: "\ue617",
            relation: "各图形样式属性",
            children: [
              {
                id: "SubTreeNode2",
                label: "rect矩形",
                text: "\ue618"
              },
              {
                id: "id1",
                label: "ellipse椭圆",
                text: "\ue6fc",
                children: [
                  {
                    id: "SubTreeNode1.2.1",
                    label: "polygon多边形",
                    text: "\ue701"
                  },
                  {
                    id: "SubTreeNode4",
                    label: "fan扇形",
                    text: "\ue702"
                  }
                ]
              }
            ]
          },
          {
            id: "SubTreeNode3",
            label: "image图片",
            text: "\ue700",
            children: [
              {
                id: "SubTreeNode3.1",
                label: "marker标记",
                text: "\ue6ff"
              },
              {
                id: "SubTreeNode3.2",
                label: "path路径",
                text: "\ue6fe"
              }
            ]
          },
          {
            id: "SubTreeNode5",
            label: "text文本",
            relation: "属性",
            text: "\ue6fd",
            backgroundConfig: {
              fill: "green"
            },
            style: {
              fill: "white"
            },
            labelCfg: {
              style: {
                fill: "Coral"
              }
            },
            children: [
              {
                id: "SubTreeNode1.2.1",
                label: "dom（svg）渲染",
                text: "\ue703",
                relation: "通话",
                backgroundConfig: {
                  fill: "Coral"
                },
                style: {
                  fill: "#fff"
                },
                labelCfg: {
                  style: {
                    fill: "Coral"
                  }
                }
              },
              {
                id: "SubTreeNode3.3",
                label: "节点和边",
                text: "\ue704",
                relation: "图形属性",
                backgroundConfig: {
                  fill: "Coral"
                },
                style: {
                  fill: "#fff"
                },
                labelCfg: {
                  style: {
                    fill: "Coral"
                  }
                }
              }
            ]
          },
          {
            id: "SubTreeNode6",
            label: "测试",
            relation: "测试连接线",
            text: "\ue705"
          }
        ]
      };
      // 超文本省略
      console.log(data, "009uu");
      const len = data.length;
      for (var i = 0; i < len; i++) {
        var item = data[i];
        if (item.children && item.children.length != 0) {
          var children = item.children;
          // console.log(children,'pppp')
          debugger;
          for (var j = 0; j < children.length; j++) {
            data[len + j] = children[j];
            children[j].label = fittingString(
              children[j].label,
              children[j].size,
              globalFontSize
            );

            console.log(children[j]);
          }
          len = data.length;
        }
      }
      // data.forEach(function (data) {
      data.label = fittingString(data.label, data.size, globalFontSize);
      // });
      // data.edges.forEach(function (edge) {
      //   edge.label = fittingString(edge.label, 120, globalFontSize);
      // });

      // ？结束
      // 增加元素
      graph.on("node:click", evt => {
        const { item, target } = evt;
        const targetType = target.get("type");
        const name = target.get("name");

        // 增加元素
        if (targetType === "marker") {
          const model = item.getModel();
          if (name === "add-item") {
            if (!model.children) {
              model.children = [];
            }
            const id = `n-${Math.random()}`;
            model.children.push({
              id,
              label: id.substr(0, 8),
              text: "\ue704"
              //  icon: {
              //           style: {
              //             fill: 'black',
              //             stroke: '#e6fffb'
              //           },
              //           img: 'https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Q_FQT6nwEC8AAAAAAAAAAABkARQnAQ'
              //         }
            });
            graph.updateChild(model, model.id);
          } else if (name === "remove-item") {
            graph.removeChild(model.id);
          }
        }
      });

      graph.data(data);
      graph.render();
    }
  }
};
</script>
<style scoped>
/* @import '/static/icons/iconfont.css'; */
@import "../assets/icons/iconfont.css";
/*  npm install insert-css */
/* 提示框的样式 */
.g6-tooltip {
  /* border: 1px solid #e2e2e2;
      border-radius: 4px;
      font-size: 12px;
      color: #545454;
      background-color: rgba(255, 255, 255, 0.9);
      padding: 10px 8px;
      box-shadow: rgb(174, 174, 174) 0px 0px 10px; */
}
</style>
